<template>
  <div class="flex w-full p-0 flex-wrap">
    <div class="block py-7 text-center flex-1">
      <span
        class="demonstration block text-[var(--el-text-color-secondary)] text-sm mb-5"
        >{{ $t('global.calendar.selectDate') }}</span
      >
      <el-date-picker
        v-model="value"
        type="daterange"
        unlink-panels
        range-separator="To"
        start-placeholder="Start date"
        end-placeholder="End date"
        :shortcuts="shortcuts"
        :size="size"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
const emit = defineEmits(['change']);

const size = ref<'default' | 'large' | 'small'>('default');

const value = ref([undefined, undefined] as undefined[] | Date[]);

const fromDate = computed(() => {
  if (value.value)
    return value.value[0] instanceof Date ? value.value[0] : undefined;
});
const toDate = computed(() => {
  if (value.value)
    return value.value[1] instanceof Date ? value.value[1] : undefined;
});

watch([fromDate, toDate], () => {
  emit('change', {
    fromDate,
    toDate,
  });
});

const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
</script>
